import { getStoreList, getShopArea } from '@src/api/mall/store'
import { getShops } from "@src/api/catering";
import { queryNearbyShopList, queryNearbyShopList_booking } from "@src/api/reservation";
import { storeBindingsBehavior } from "mobx-miniprogram-bindings";
import router from "@src/router";
import mall from "@src/store/mall";
import base from "@src/store/base";
Component({
    behaviors: [storeBindingsBehavior],
    storeBindings: [{
        store: base,
        fields: ['themeColor', 'themeTitleColor']
    }, {
        store: mall,
        actions: ['initLocation']
    }],
    properties: {
        storeInfo: {
            type: Object,
            value:{}
        },
        listIndex: {
            type: String,
            value:''
        }, //仅用于图片懒加载
    },
    data: {
        storeList: [],
        searchList: [],
        isShowAllList: true,
        ifSearch: false,

        // 地区
        isPlace: false,
        cityIndex: 0,
        areaIndex: 0,
        selectCityName: '',//点击的城市，用于搜索区
        placeTxt: '全部门店',
        allPlace: {
            cityList: [],
            areaList: []
        },
        noMore: false
    },
    lifetimes: {
        attached: function () { }
    },
    observers: {
        'storeInfo'() {}
    },

    methods: {
        //监听子组件传过来的输入框的值
        inputValueFunc(detail) {
            if (detail.detail.length > 0) {
                const keywords = detail.detail
                let list = this.data.storeList
                let len = list.length;
                let arr = [];
                for (let i = 0; i < len; i++) {
                    //如果字符串中不包含目标字符会返回-1
                    let name = list[i].name;
                    if (name.indexOf(keywords) >= 0) {
                        arr.push(list[i]);
                    }
                    this.setData({
                        isShowAllList: false,
                        ifSearch: true,
                    })
                }
                this.setData({
                    searchList: arr,
                    isPlace: false,
                    keywords
                })
                if (this.data.searchList.length > 0) {
                    this.setData({ noMore: true })
                } else {
                    this.setData({ noMore: false })
                }
            } else {
                this.setData({
                    isShowAllList: true,
                    isPlace: false,
                    keywords: ''
                })
                this.getStoreListFunc()
            }
        },
        onLogin() {
            this.getShopAreaFunc()
            this.initLocation().then(res => {
                this.setData({ latitude: res.latitude, longitude: res.longitude })
                this.getStoreListFunc()
            }).catch(() => {
                this.getStoreListFunc()
            })
        },
        getStoreListFunc() {
            let data = {
                latitude: this.data.latitude,
                longitude: this.data.longitude,
                city: this.data.selectCityName,
                area: this.data.selectAreaName,
                name: this.data.keywords
            };
            let { storeType } = this.properties.storeInfo
            let api = ''
            if (storeType === 'catering') {
                api = getShops
            } else if (storeType === 'reservation') {
                api = queryNearbyShopList
            } else if (storeType === 'booking') {
                api = queryNearbyShopList_booking
            } else {
                api = getStoreList
            }
            this.setData({
                storeList: '',
                searchList: '',
                noMore: false
            })
            api(data).then(res => {
                res.data.forEach((item, index) => {
                    if (item.distance) {
                        if (item.distance < 1000) {
                            item.distance = item.distance.toFixed(2) + "m";
                        } else {
                            item.distance = (Math.round(item.distance / 100) / 10).toFixed(1) + "km";
                        }
                    }
                })
                this.setData({
                    storeList: res.data
                })
                if (this.data.storeList.length > 0) {
                    this.setData({
                        isShowAllList: true,
                        noMore: true
                    })
                } else {
                    this.setData({
                        isShowAllList: false,
                        ifSearch: true,
                        noMore: false
                    })
                }
            }).catch(err => {
            })
        },
        //点击店铺
        chooseShop(e) {
            let item = e.currentTarget.dataset.item;
            if (!item.isOpenTime) {
                wx.showToast({ title: "该门店休息中", icon: "none" });
                return;
            }
            let { storeType } = this.properties.storeInfo
            if (storeType === 'catering' || storeType === 'reservation' || storeType === 'booking') {
                // router.back()传值
                const pages = getCurrentPages()
                const prevPage = pages[pages.length - 2]
                prevPage.setData({
                    storeData: item
                })
                router.back()

                // 接收页通过以下方式接收：
                // onShow(){
                //     const pages = getCurrentPages()
                //     const currPage = pages[pages.length - 1]
                //     console.log('接收门店列表的数据 currPage', currPage.data.storeData)
                // },
            } else {
                router.push({ name: "mall/store-detail", params: { storeId: item.storeId } })
            }
        },

        // 获取门店区域
        getShopAreaFunc() {
            let { businessId } = getApp().globalData.extConfig;
            let { storeType } = this.properties.storeInfo
            let data = {
                businessId,
                name: this.data.selectCityName ? this.data.selectCityName : '',
                type: storeType === 'catering' ? 2 : storeType === 'reservation' ? 4 : storeType === 'booking' ? 3 : 1
            };
            getShopArea(data).then(res => {
                // console.log('获取门店区域', res)
                if (data.name) {
                    this.data.allPlace.areaList = res.data
                } else {
                    this.data.allPlace.cityList = res.data
                }
                this.setData({ allPlace: this.data.allPlace })

                // 根据placeTxt查找并选中区
                let areaIndex = ''
                this.data.allPlace.areaList.forEach((el, index) => {
                    if (el.name === this.data.placeTxt) {
                        areaIndex = index
                    }
                })
                this.setData({ areaIndex })
            })
        },
        // 城市显示/隐藏
        handleShow() {
            this.setData({ isPlace: !this.data.isPlace })
            this.data.allPlace.cityList.forEach((el, index) => {
                if (el.checked) {
                    this.setData({ cityIndex: index, selectCityName: el.name })
                    this.getShopAreaFunc()
                }
            })
        },
        cityBtn(e) {
            let index = e.currentTarget.dataset.index
            let selectCityName = this.data.allPlace.cityList[index].name
            this.setData({ selectCityName, cityIndex: index, areaIndex: '' })
            this.getShopAreaFunc()
            if (index === 0) {
                this.setData({ isPlace: false, placeTxt: selectCityName, selectAreaName: '' })
                this.data.allPlace.cityList.forEach((el, index) => {
                    if (index > 0) {
                        el.checked = false
                    } else {
                        el.checked = true
                    }
                })
                this.getStoreListFunc()
            }
        },
        areaBtn(e) {
            let index = e.currentTarget.dataset.index
            let placeTxt = this.data.allPlace.areaList[index].name

            this.data.allPlace.cityList.forEach((el) => {
                el.checked = false
            })
            this.data.allPlace.cityList[this.data.cityIndex].checked = true
            this.setData({ isPlace: false, allPlace: this.data.allPlace, areaIndex: index })
            if (index > 0) {
                this.setData({ placeTxt })
            } else {
                let name = this.data.allPlace.cityList[this.data.cityIndex].name
                this.setData({ placeTxt: name })
            }
            this.setData({ selectAreaName: placeTxt })

            this.getStoreListFunc()
        },
        //调起导航
        goLocation(e) {
            let dataObj = e.currentTarget.dataset.item;
            wx.openLocation({
                name: dataObj.name,
                address: dataObj.address,
                latitude: dataObj.latitude,
                longitude: dataObj.longitude,
                scale: 18
            })
        },
        //调起手机拨号功能
        telphone(e) {
            let phone = e.currentTarget.dataset.phone
            if (phone) {
                wx.makePhoneCall({
                    phoneNumber: e.currentTarget.dataset.phone, //模拟测试
                    success: function () {
                        console.log("拨打电话成功！")
                    },
                    fail: function () {
                        console.log("拨打电话失败！")
                    }
                })
            } else {
                wx.showToast({ title: "该店铺暂未设置客服电话", icon: "none" });
            }
        },
        // 触底
        onReachBottom() { },
        // 下拉刷新
        onPullDownRefresh() {
            this.getShopAreaFunc()
            this.getStoreListFunc()
            wx.stopPullDownRefresh()
        }
    }
})
